package com.cskaoyan.utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

/**
 * 创建日期: 2021/11/29 11:34
 *
 * @author ciggar
 */
public class MybatisUtils {

    static SqlSession sqlSession;

    static {

        // 获取SqlSessionFactory，需要先获取SqlSessionFactoryBuilder
        SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();

        // 获取主配置文件输入流
//        ClassLoader classLoader = MybatisMain.class.getClassLoader();
//        InputStream stream = classLoader.getResourceAsStream("mybatis-config.xml");

        InputStream stream = null;
        try {
            stream = Resources.getResourceAsStream("mybatis-config.xml");
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 获取SqlSessionFactory
        SqlSessionFactory sqlSessionFactory = builder.build(stream);

        // 获取SqlSession SqlSession可以帮助我们去执行SQL语句
        sqlSession = sqlSessionFactory.openSession();
    }

    public static SqlSession getSqlSession() {
        return sqlSession;
    }
}
